'use client';

import React, { createContext, useContext, useState, useEffect } from 'react';

// 定义可选的主题颜色
export type ThemeColor = 'orange' | 'blue' | 'green' | 'purple' | 'red';

// 定义主题上下文类型
type ThemeContextType = {
  themeColor: ThemeColor;
  setThemeColor: (color: ThemeColor) => void;
};

// 创建主题上下文
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

// 主题颜色配置
export const themeColorConfig = {
  orange: {
    primary: {
      50: '#fff7ed',
      100: '#ffedd5',
      200: '#fed7aa',
      300: '#fdba74',
      400: '#fb923c',
      500: '#f97316',
      600: '#ea580c',
      700: '#c2410c',
      800: '#9a3412',
      900: '#7c2d12',
    }
  },
  blue: {
    primary: {
      50: '#eff6ff',
      100: '#dbeafe',
      200: '#bfdbfe',
      300: '#93c5fd',
      400: '#60a5fa',
      500: '#3b82f6',
      600: '#2563eb',
      700: '#1d4ed8',
      800: '#1e40af',
      900: '#1e3a8a',
    }
  },
  green: {
    primary: {
      50: '#f0fdf4',
      100: '#dcfce7',
      200: '#bbf7d0',
      300: '#86efac',
      400: '#4ade80',
      500: '#22c55e',
      600: '#16a34a',
      700: '#15803d',
      800: '#166534',
      900: '#14532d',
    }
  },
  purple: {
    primary: {
      50: '#faf5ff',
      100: '#f3e8ff',
      200: '#e9d5ff',
      300: '#d8b4fe',
      400: '#c084fc',
      500: '#a855f7',
      600: '#9333ea',
      700: '#7e22ce',
      800: '#6b21a8',
      900: '#581c87',
    }
  },
  red: {
    primary: {
      50: '#fef2f2',
      100: '#fee2e2',
      200: '#fecaca',
      300: '#fca5a5',
      400: '#f87171',
      500: '#ef4444',
      600: '#dc2626',
      700: '#b91c1c',
      800: '#991b1b',
      900: '#7f1d1d',
    }
  }
};

// 主题提供者组件
export function ThemeProvider({ children }: { children: React.ReactNode }) {
  // 尝试从localStorage获取保存的主题，默认为橙色
  const [themeColor, setThemeColor] = useState<ThemeColor>('orange');
  
  // 初始化时从localStorage加载主题
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme') as ThemeColor;
    if (savedTheme && Object.keys(themeColorConfig).includes(savedTheme)) {
      setThemeColor(savedTheme);
    }
  }, []);
  
  // 当主题变化时，更新localStorage和CSS变量
  useEffect(() => {
    localStorage.setItem('theme', themeColor);
    
    // 更新CSS变量
    const colors = themeColorConfig[themeColor].primary;
    Object.entries(colors).forEach(([key, value]) => {
      document.documentElement.style.setProperty(`--color-primary-${key}`, value);
    });
  }, [themeColor]);
  
  return (
    <ThemeContext.Provider value={{ themeColor, setThemeColor }}>
      {children}
    </ThemeContext.Provider>
  );
}

// 自定义Hook，用于在组件中使用主题
export function useTheme() {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
} 